<template>
  <transition appear name="fadeIn">
      <div
      class="message"
      :style="{
        backgroundColor: colorMap[type].backgroundColor,
        color: colorMap[type].color,
        top: verticalOffset+'px',
      }"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
    >
      <slot>
        <p>{{ message }}</p>
      </slot>
    </div>
  </transition>
</template>



<script type="text/babel">
export default {
  data() {
    return {
      colorMap: {
        success: { backgroundColor: "#7ee74a99", color: "#04853999" },
        error: { backgroundColor: "#e9505899", color: "#ac131a99" },
      },
      visible: false,
      message: "",
      duration: 5000,
      type: "success",
      iconClass: "",
      customClass: "",
      onClose: null,
      showClose: false,
      closed: false,
      verticalOffset: 20,
      timer: null,
      dangerouslyUseHTMLString: false,
      center: false,
    };
  },

  computed: {
    positionStyle() {
      return {
        top: `${this.verticalOffset}px`,
      };
    },
  },

  watch: {
    closed(newVal) {
      if (newVal) {
        this.visible = false;
      }
    },
  },

  methods: {
    handleAfterLeave() {
      this.$destroy(true);
      this.$el.parentNode.removeChild(this.$el);
    },

    close() {
      this.closed = true;
      if (typeof this.onClose === "function") {
        this.onClose(this);
      }
    },

    clearTimer() {
      clearTimeout(this.timer);
    },

    startTimer() {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          if (!this.closed) {
            this.close();
          }
        }, this.duration);
      }
    },
    keydown(e) {
      if (e.keyCode === 27) {
        // esc关闭消息
        if (!this.closed) {
          this.close();
        }
      }
    },
  },
  mounted() {
    this.startTimer();
    document.addEventListener("keydown", this.keydown);
  },
  beforeDestroy() {
    document.removeEventListener("keydown", this.keydown);
  },
};
</script>

<style lang="less" scoped>
@import url("../css/comment/animate.css");
.message {
  position: absolute;
  width: 18%;
  font-size: 18px;
  height: 40px;
  text-align: center;
  margin: auto;
  left: 0;
  right: 0;
  border-radius: 10px;
  p {
    margin: 0;
    line-height: 40px;
  }
}
</style>